<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面头部 -->
    <page-header 
      title="SEO数据统计" 
      subtitle="跟踪和分析网站SEO关键指标的趋势和表现"
    >
      <template #extra>
        <div class="flex gap-3">
          <select
            v-model="dateRange"
            class="form-input w-48"
            @change="refreshCharts"
          >
            <option value="7days">近7天</option>
            <option value="30days">近30天</option>
            <option value="90days">近90天</option>
            <option value="12months">近12个月</option>
          </select>
          <button class="btn btn-primary">
            <i class="fa fa-download mr-1"></i>导出报告
          </button>
        </div>
      </template>
    </page-header>
    
    <!-- 主要内容区 -->
    <div class="px-4 sm:px-6 lg:px-8 py-6">
      <!-- 核心指标卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow p-6 transform transition-all hover:scale-[1.02]">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">自然搜索流量</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.organicTraffic }}</h3>
              <p class="text-xs text-gray-500 mt-1">访问量（基于所选时段）</p>
            </div>
            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
              <i class="fa fa-line-chart text-blue-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="flex items-center" :class="stats.organicTrafficChange >= 0 ? 'text-green-600' : 'text-red-600'">
              <i :class="stats.organicTrafficChange >= 0 ? 'fa fa-arrow-up mr-1' : 'fa fa-arrow-down mr-1'"></i>
              {{ Math.abs(stats.organicTrafficChange) }}%
            </span>
            <span class="text-gray-500 ml-2">较上一周期</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6 transform transition-all hover:scale-[1.02]">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">平均排名</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.averageRank }}</h3>
              <p class="text-xs text-gray-500 mt-1">监控关键词的平均排名</p>
            </div>
            <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
              <i class="fa fa-trophy text-green-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class=" flex items-center" :class="stats.averageRankChange <= 0 ? 'text-green-600' : 'text-red-600'">
              <!-- 排名下降是好事，所以变化值为负时显示上升箭头 -->
              <i :class="stats.averageRankChange <= 0 ? 'fa fa-arrow-down mr-1' : 'fa fa-arrow-up mr-1'"></i>
              {{ Math.abs(stats.averageRankChange) }}
            </span>
            <span class="text-gray-500 ml-2">较上一周期</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6 transform transition-all hover:scale-[1.02]">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">新发现关键词</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.newKeywords }}</h3>
              <p class="text-xs text-gray-500 mt-1">新增有排名的关键词</p>
            </div>
            <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center">
              <i class="fa fa-plus-circle text-purple-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="text-green-600 flex items-center">
              <i class="fa fa-arrow-up mr-1"></i>{{ stats.newKeywordsGrowth }}%
            </span>
            <span class="text-gray-500 ml-2">较上一周期</span>
          </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6 transform transition-all hover:scale-[1.02]">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-500">跳出率</p>
              <h3 class="text-2xl font-bold text-gray-900 mt-1">{{ stats.bounceRate }}%</h3>
              <p class="text-xs text-gray-500 mt-1">自然搜索访客的跳出率</p>
            </div>
            <div class="w-10 h-10 rounded-full bg-yellow-100 flex items-center justify-center">
              <i class="fa fa-sign-out text-yellow-600"></i>
            </div>
          </div>
          <div class="mt-4 flex items-center text-sm">
            <span class="flex items-center" :class="stats.bounceRateChange <= 0 ? 'text-green-600' : 'text-red-600'">
              <i :class="stats.bounceRateChange <= 0 ? 'fa fa-arrow-down mr-1' : 'fa fa-arrow-up mr-1'"></i>
              {{ Math.abs(stats.bounceRateChange) }}%
            </span>
            <span class="text-gray-500 ml-2">较上一周期</span>
          </div>
        </div>
      </div>
      
      <!-- 趋势图表区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- 自然搜索流量趋势 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">自然搜索流量趋势</h3>
          <div class="h-80">
            <canvas id="organicTrafficChart"></canvas>
          </div>
        </div>
        
        <!-- 平均排名趋势 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">平均排名趋势</h3>
          <div class="h-80">
            <canvas id="averageRankChart"></canvas>
          </div>
        </div>
      </div>
      
      <!-- 关键词分布图表 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- 关键词排名分布 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">关键词排名分布</h3>
          <div class="h-80">
            <canvas id="keywordDistributionChart"></canvas>
          </div>
        </div>
        
        <!-- 搜索引擎分布 -->
        <div class="bg-white rounded-lg shadow-md p-6">
          <h3 class="text-lg font-semibold text-gray-800 mb-4">搜索引擎流量分布</h3>
          <div class="h-80">
            <canvas id="searchEngineChart"></canvas>
          </div>
        </div>
      </div>
      
      <!-- 热门关键词表格 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden mb-6">
        <div class="p-6 border-b border-gray-200">
          <h3 class="text-lg font-semibold text-gray-800">带来流量的热门关键词</h3>
          <p class="text-sm text-gray-500 mt-1">基于自然搜索流量排序的前20个关键词</p>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  关键词
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  排名
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  搜索量
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  流量
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  点击率
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  排名变化
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="keyword in topKeywords" :key="keyword.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">{{ keyword.text }}</div>
                  <div class="text-xs text-gray-500">{{ keyword.url }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                    {{ keyword.rank }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ keyword.searchVolume }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ keyword.traffic }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="w-full bg-gray-200 rounded-full h-2">
                    <div 
                      class="h-2 rounded-full bg-green-500"
                      :style="{ width: keyword.ctr + '%' }"
                    ></div>
                  </div>
                  <div class="text-xs text-gray-500 mt-1">{{ keyword.ctr }}%</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="text-sm font-medium"
                    :class="keyword.rankChange > 0 ? 'text-green-600' : keyword.rankChange < 0 ? 'text-red-600' : 'text-gray-500'"
                  >
                    <i v-if="keyword.rankChange > 0" class="fa fa-arrow-up mr-1"></i>
                    <i v-if="keyword.rankChange < 0" class="fa fa-arrow-down mr-1"></i>
                    {{ keyword.rankChange !== 0 ? Math.abs(keyword.rankChange) : '-' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <!-- 分页 -->
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex items-center justify-between">
          <div class="flex-1 flex justify-between sm:hidden">
            <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              上一页
            </button>
            <button class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              下一页
            </button>
          </div>
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                显示第 <span class="font-medium">1</span> 到 <span class="font-medium">{{ Math.min(10, topKeywords.length) }}</span> 条，共 <span class="font-medium">{{ topKeywords.length }}</span> 条记录
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <button class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" disabled>
                  <span class="sr-only">上一页</span>
                  <i class="fa fa-chevron-left text-xs"></i>
                </button>
                <button class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-primary text-sm font-medium text-white">
                  1
                </button>
                <button class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                  <span class="sr-only">下一页</span>
                  <i class="fa fa-chevron-right text-xs"></i>
                </button>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 页面性能统计 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="p-6 border-b border-gray-200">
          <h3 class="text-lg font-semibold text-gray-800">热门页面性能统计</h3>
          <p class="text-sm text-gray-500 mt-1">基于自然搜索流量排序的前10个页面</p>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  页面
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  流量
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  平均排名
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  跳出率
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  平均停留时间
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  监控关键词
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="page in topPages" :key="page.id" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900 truncate max-w-xs">{{ page.title }}</div>
                  <div class="text-xs text-gray-500 truncate max-w-xs">{{ page.url }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ page.traffic }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                    {{ page.avgRank }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ page.bounceRate }}%
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ page.avgTimeOnPage }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ page.keywordCount }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Chart, registerables } from 'chart.js'
import { 
  getSeoStats, 
  getTrafficTrend, 
  getRankTrend, 
  getKeywordDistribution, 
  getSearchEngineDistribution,
  getTopKeywords,
  getTopPages
} from '@/api/seo'

// 注册Chart.js组件
Chart.register(...registerables)

// 状态变量
const dateRange = ref('30days')
const stats = ref({
  organicTraffic: 0,
  organicTrafficChange: 0,
  averageRank: 0,
  averageRankChange: 0,
  newKeywords: 0,
  newKeywordsGrowth: 0,
  bounceRate: 0,
  bounceRateChange: 0
})

const topKeywords = ref([])
const topPages = ref([])

// 图表实例
let organicTrafficChart = null
let averageRankChart = null
let keywordDistributionChart = null
let searchEngineChart = null

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await getSeoStats(dateRange.value)
    stats.value = response.data
  } catch (error) {
    console.error('获取SEO统计数据失败:', error)
  }
}

// 获取热门关键词
const fetchTopKeywords = async () => {
  try {
    const response = await getTopKeywords(dateRange.value)
    topKeywords.value = response.data
  } catch (error) {
    console.error('获取热门关键词失败:', error)
  }
}

// 获取热门页面
const fetchTopPages = async () => {
  try {
    const response = await getTopPages(dateRange.value)
    topPages.value = response.data
  } catch (error) {
    console.error('获取热门页面失败:', error)
  }
}

// 初始化自然搜索流量图表
const initOrganicTrafficChart = async () => {
  try {
    const response = await getTrafficTrend(dateRange.value)
    const data = response.data
    
    const ctx = document.getElementById('organicTrafficChart').getContext('2d')
    
    // 销毁现有图表
    if (organicTrafficChart) {
      organicTrafficChart.destroy()
    }
    
    organicTrafficChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: data.labels,
        datasets: [{
          label: '自然搜索流量',
          data: data.values,
          borderColor: '#3b82f6',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          tension: 0.3,
          fill: true,
          pointBackgroundColor: '#3b82f6'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          tooltip: {
            mode: 'index',
            intersect: false
          },
          legend: {
            display: false
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              drawBorder: false
            }
          },
          x: {
            grid: {
              display: false
            }
          }
        },
        interaction: {
          mode: 'nearest',
          axis: 'x',
          intersect: false
        }
      }
    })
  } catch (error) {
    console.error('初始化流量趋势图表失败:', error)
  }
}

// 初始化平均排名图表
const initAverageRankChart = async () => {
  try {
    const response = await getRankTrend(dateRange.value)
    const data = response.data
    
    const ctx = document.getElementById('averageRankChart').getContext('2d')
    
    // 销毁现有图表
    if (averageRankChart) {
      averageRankChart.destroy()
    }
    
    averageRankChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: data.labels,
        datasets: [{
          label: '平均排名',
          data: data.values,
          borderColor: '#10b981',
          backgroundColor: 'rgba(16, 185, 129, 0.1)',
          tension: 0.3,
          fill: true,
          pointBackgroundColor: '#10b981'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          tooltip: {
            mode: 'index',
            intersect: false
          },
          legend: {
            display: false
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            reverse: true, // 排名图表反转Y轴，值越小（排名越前）越靠上
            grid: {
              drawBorder: false
            }
          },
          x: {
            grid: {
              display: false
            }
          }
        },
        interaction: {
          mode: 'nearest',
          axis: 'x',
          intersect: false
        }
      }
    })
  } catch (error) {
    console.error('初始化排名趋势图表失败:', error)
  }
}

// 初始化关键词分布图表
const initKeywordDistributionChart = async () => {
  try {
    const response = await getKeywordDistribution()
    const data = response.data
    
    const ctx = document.getElementById('keywordDistributionChart').getContext('2d')
    
    // 销毁现有图表
    if (keywordDistributionChart) {
      keywordDistributionChart.destroy()
    }
    
    keywordDistributionChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['1-10', '11-30', '31-50', '51-100', '101-200', '200+'],
        datasets: [{
          label: '关键词数量',
          data: data.values,
          backgroundColor: [
            '#10b981', // 绿色 - Top 10
            '#3b82f6', // 蓝色 - 11-30
            '#6366f1', // 靛蓝色 - 31-50
            '#f59e0b', // 琥珀色 - 51-100
            '#ef4444', // 红色 - 101-200
            '#6b7280'  // 灰色 - 200+
          ],
          borderRadius: 4
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                const label = context.dataset.label || '';
                const value = context.raw || 0;
                const total = data.values.reduce((a, b) => a + b, 0);
                const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                return `${label}: ${value} (${percentage}%)`;
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            grid: {
              drawBorder: false
            }
          },
          x: {
            grid: {
              display: false
            },
            title: {
              display: true,
              text: '搜索引擎排名位置'
            }
          }
        }
      }
    })
  } catch (error) {
    console.error('初始化关键词分布图表失败:', error)
  }
}

// 初始化搜索引擎分布图表
const initSearchEngineChart = async () => {
  try {
    const response = await getSearchEngineDistribution(dateRange.value)
    const data = response.data
    
    const ctx = document.getElementById('searchEngineChart').getContext('2d')
    
    // 销毁现有图表
    if (searchEngineChart) {
      searchEngineChart.destroy()
    }
    
    searchEngineChart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: data.labels,
        datasets: [{
          data: data.values,
          backgroundColor: [
            '#3b82f6',
            '#10b981',
            '#f59e0b',
            '#8b5cf6',
            '#ec4899'
          ],
          borderWidth: 0,
          hoverOffset: 4
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'right'
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                const label = context.label || '';
                const value = context.raw || 0;
                const total = data.values.reduce((a, b) => a + b, 0);
                const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                return `${label}: ${value} (${percentage}%)`;
              }
            }
          }
        },
        cutout: '65%'
      }
    })
  } catch (error) {
    console.error('初始化搜索引擎分布图表失败:', error)
  }
}

// 刷新所有图表
const refreshCharts = async () => {
  await Promise.all([
    initOrganicTrafficChart(),
    initAverageRankChart(),
    initSearchEngineChart(),
    fetchStats(),
    fetchTopKeywords(),
    fetchTopPages()
  ])
}

// 页面加载时初始化数据
onMounted(async () => {
  await Promise.all([
    fetchStats(),
    fetchTopKeywords(),
    fetchTopPages(),
    initOrganicTrafficChart(),
    initAverageRankChart(),
    initKeywordDistributionChart(),
    initSearchEngineChart()
  ])
})

// 监听日期范围变化，刷新数据
watch(dateRange, refreshCharts)
</script>
